from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from .models import Merchant, MenuItem
from orders.models import Order
from django.db.models import Avg
from datetime import datetime

def merchant_list(request):
    """商家列表视图"""
    merchants = Merchant.objects.all().annotate(
        avg_rating=Avg('order__rating')
    ).order_by('-avg_rating')
    return render(request, 'merchant_list.html', {'merchants': merchants})

def merchant_detail(request, merchant_id):
    """商家详情视图"""
    merchant = get_object_or_404(Merchant, id=merchant_id)
    menu_items = merchant.menuitem_set.filter(is_available=True)
    return render(request, 'merchant_detail.html', {
        'merchant': merchant,
        'menu_items': menu_items
    })

def menu(request, merchant_id):
    """商家菜单视图"""
    merchant = get_object_or_404(Merchant, id=merchant_id)
    categories = merchant.menuitem_set.values_list('category', flat=True).distinct()
    menu_items = {}
    for category in categories:
        menu_items[category] = merchant.menuitem_set.filter(
            category=category,
            is_available=True
        )
    return render(request, 'menu.html', {
        'merchant': merchant,
        'categories': categories,
        'menu_items': menu_items
    })

@login_required
def merchant_dashboard(request):
    """商家管理后台"""
    if not hasattr(request.user, 'merchant'):
        messages.error(request, '您不是商家用户')
        return redirect('home')
    
    merchant = request.user.merchant
    pending_orders = Order.objects.filter(
        merchant=merchant,
        status='pending'
    ).order_by('-created_at')
    
    today_orders = Order.objects.filter(
        merchant=merchant,
        created_at__date=datetime.now().date()
    )
    
    context = {
        'merchant': merchant,
        'pending_orders': pending_orders,
        'today_orders': today_orders,
        'total_orders': today_orders.count(),
        'total_amount': sum(order.total_amount for order in today_orders)
    }
    return render(request, 'merchant_dashboard.html', context)

@login_required
def pending_orders(request):
    """待处理订单列表"""
    if not hasattr(request.user, 'merchant'):
        return JsonResponse({'status': 'error', 'message': '无权限访问'})
    
    orders = Order.objects.filter(
        merchant=request.user.merchant,
        status='pending'
    ).order_by('-created_at')
    return render(request, 'pending_orders.html', {'orders': orders})

@login_required
def completed_orders(request):
    """已完成订单列表"""
    if not hasattr(request.user, 'merchant'):
        return JsonResponse({'status': 'error', 'message': '无权限访问'})
    
    orders = Order.objects.filter(
        merchant=request.user.merchant,
        status='completed'
    ).order_by('-completed_at')
    return render(request, 'completed_orders.html', {'orders': orders})

@login_required
def manage_menu(request):
    """菜单管理"""
    if not hasattr(request.user, 'merchant'):
        return JsonResponse({'status': 'error', 'message': '无权限访问'})
    
    menu_items = MenuItem.objects.filter(merchant=request.user.merchant)
    return render(request, 'manage_menu.html', {'menu_items': menu_items})

@login_required
def add_menu_item(request):
    """添加菜品"""
    if not hasattr(request.user, 'merchant'):
        return JsonResponse({'status': 'error', 'message': '无权限访问'})
    
    if request.method == 'POST':
        name = request.POST.get('name')
        price = request.POST.get('price')
        description = request.POST.get('description')
        category = request.POST.get('category')
        image = request.FILES.get('image')
        
        MenuItem.objects.create(
            merchant=request.user.merchant,
            name=name,
            price=price,
            description=description,
            category=category,
            image=image
        )
        messages.success(request, '菜品添加成功！')
        return redirect('manage_menu')
    
    return render(request, 'add_menu_item.html')

@login_required
def edit_menu_item(request, item_id):
    """编辑菜品"""
    if not hasattr(request.user, 'merchant'):
        return JsonResponse({'status': 'error', 'message': '无权限访问'})
    
    item = get_object_or_404(MenuItem, id=item_id, merchant=request.user.merchant)
    
    if request.method == 'POST':
        item.name = request.POST.get('name')
        item.price = request.POST.get('price')
        item.description = request.POST.get('description')
        item.category = request.POST.get('category')
        if 'image' in request.FILES:
            item.image = request.FILES['image']
        item.save()
        
        messages.success(request, '菜品更新成功！')
        return redirect('manage_menu')
    
    return render(request, 'edit_menu_item.html', {'item': item})

@login_required
def delete_menu_item(request, item_id):
    """删除菜品"""
    if not hasattr(request.user, 'merchant'):
        return JsonResponse({'status': 'error', 'message': '无权限访问'})
    
    item = get_object_or_404(MenuItem, id=item_id, merchant=request.user.merchant)
    item.delete()
    messages.success(request, '菜品已删除！')
    return redirect('manage_menu')
